﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using FantastPlatform.Community.IMode;
using System.Net;
using System.Configuration;
using System.Text;

namespace FantastPlatform.Community.UI.Service
{
    public partial class CarSearchService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            ICarService carService = ServiceFactory.CreateService<ICarService>();
            ICar car;
            IList<ICar> carList;
            IList<Sort> sorts = new List<Sort>();
            ConditionGroup group = new ConditionGroup();
            int totalCount = 0;
            Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
            group.Conditions.Add(enableCondition);
            switch (Action)
            {
                case "Search":
                    carList = carService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    var objperson = from n in carList
                                    where n.Person != null
                                    select new
                                    {
                                        Id = n.Id,
                                        Number = n.Number,
                                        PersonName = n.Person.Name,
                                        CarType = n.CarType,
                                        Address = GetHouseAddressByPersonId(n.Person.Id)
                                    };
                    ReturnList(totalCount, objperson.ToList());

                    break;

                case "SearchByCondition":
                    string Searchjson = RepairString(Data);
                    CarView carview = JsonToEntity<CarView>(Searchjson);
                    if (!string.IsNullOrEmpty(carview.Number))
                    {
                        Condition condition2 = new Condition() { Type = typeof(string).FullName, Field = "Number", Value1 = '%' + carview.Number + '%', Comparison = Comparisons.Like, Relation = Relations.And };
                        group.Conditions.Add(condition2);
                    }
                    if (!string.IsNullOrEmpty(carview.PersonName))
                    {
                        Condition condition3 = new Condition() { Type = typeof(string).FullName, Field = "Person.Name", Value1 = '%' + carview.PersonName + '%', Comparison = Comparisons.Like, Relation = Relations.And };
                        group.Conditions.Add(condition3);
                    }
                    carList = carService.Search(group, sorts, PageSize, SelfPage, out totalCount);

                    var obj = from n in carList
                              select new
                              {
                                  Id = n.Id,
                                  Number = n.Number,
                                  PersonName = n.Person.Name,
                                  CarType = n.CarType,
                                  Address = GetHouseAddressByPersonId(n.Person.Id)
                              };
                    var objList = obj.ToList();
                    ReturnList(objList.Count, objList);
                    break;

                case "Get":
                    car = carService.Get(Id);
                    var objpersonInfo = (new
                              {
                                  Id = car.Id,
                                  Number = car.Number,
                                  PersonName = car.Person.Name,
                                  CarType = car.CarType,
                                  BaseInfo = GetHouseAddressByPersonId(car.Person.Id)
                              });
                    ReturnObj(objpersonInfo);
                    break;
                case "GetDetails":
                    car = carService.Get(Id);
                    string CarNumber = string.Empty;
                    string DetailsInfo = string.Empty;
                    if (car.CarType == "小车")
                    {
                        car.Number = car.Number.Trim();
                        if (car.Number.Contains("川A") || car.Number.Contains("川a") || car.Number.Length == 5)
                        {
                            if (car.Number.Length != 5)
                            {
                                int i = "川A".Length;
                                CarNumber = car.Number.Substring(i, car.Number.Length - i);
                            }
                            else
                            {
                                CarNumber = car.Number;
                            }
                            DetailsInfo = GetCarInfo(CarNumber);
                        }
                        string jsonStr = "{ 'success': 'true', 'data': " + DetailsInfo + "}";
                        Response.Write(jsonStr);
                        Response.End();
                    }
                    else
                    {
                        ReturnErrorMessage("该类车型不能查询详细信息！");
                    }
                    break;
            }
        }
        private string GetHouseAddressByPersonId(int personId)
        {
            try
            {
                int totalCount = 0;
                string address = "";
                if (personId == 0)
                {
                    return address;
                }
                IBusinessPersonService bpService = ServiceFactory.CreateService<IBusinessPersonService>();
                IHouseHoldPersonService hhService = ServiceFactory.CreateService<IHouseHoldPersonService>();
                ConditionGroup group = new ConditionGroup();
                group.Conditions.Add(new Condition { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });

                group.Conditions.Add(new Condition { Field = "Person.Id", Type = typeof(Int32).FullName, Value1 = personId, Relation = Relations.And });
                IList<IBusinessPerson> bPersonList = bpService.Search(group, null, Int32.MaxValue, 1, out totalCount);
                if (totalCount > 0)
                {
                    // bPersonList[0].Business.Station.Name + bPersonList[0].Business.ResponsibilityArea.Name + 
                    address = bPersonList[0].Business.Street.Name + bPersonList[0].Business.Address;
                }
                IList<IHouseHoldPerson> hhList = hhService.Search(group, null, Int32.MaxValue, 1, out totalCount);
                if (totalCount > 0)
                {
                    //hhList[0].HouseHold.HouseDistrict.Station.Name + hhList[0].HouseHold.HouseDistrict.ResponsibilityArea.Name + 
                    address = hhList[0].HouseHold.HouseDistrict.Street.Name + hhList[0].HouseHold.HouseDistrict.Address + hhList[0].HouseHold.Number;
                }
                return address;
            }
            catch (Exception)
            {
                return "";
            }

        }
        public class CarView
        {
            public int Id { get; set; }
            public string PersonName { get; set; }
            public string Number { get; set; }
        }

        static string GetCarInfo(string PlateNumber)
        {
            string carinfo = string.Empty;
            try
            {
                #region 通过请求得到车辆信息
                WebClient wc = new WebClient();
                byte[] carResponse = wc.DownloadData(ConfigurationManager.AppSettings["CarAddress"] + "&hphm=" + PlateNumber);
                string carinfoStr = Encoding.Default.GetString(carResponse);
                #endregion

                #region 处理返回的字符串
                if (carinfoStr.Length > 5000)
                {
                    carinfo = carinfoStr.Substring(1463, carinfoStr.Length - 2622);
                    carinfo = carinfo.Replace("<div align=\"center\">", "");
                    carinfo = carinfo.Replace("</div>", "");
                    carinfo = carinfo.Replace("<td width=\"12%\" bgcolor=\"#ffffee\">", "");
                    carinfo = carinfo.Replace("<td>", "");
                    carinfo = carinfo.Replace("</td>", "");
                    carinfo = carinfo.Replace("<tr>", "");
                    carinfo = carinfo.Replace("</tr>", "");
                    carinfo = carinfo.Replace("<td colspan=\"5\">", "");
                    carinfo = carinfo.Replace("<td width=\"22%\">", "");
                    carinfo = carinfo.Replace("<td width=\"11%\" bgcolor=\"#ffffee\">", "");
                    carinfo = carinfo.Replace("<td colspan=\"3\">", "");
                    carinfo = carinfo.Replace("<td bgcolor=\"#ffffee\" width=\"10%\">", "");
                    carinfo = carinfo.Replace("<td width=\"25%\">", "");
                    carinfo = carinfo.Replace("<td width=\"20%\">", "");
                    carinfo = carinfo.Replace("<td width=\"10%\" bgcolor=\"#ffffee\">", "");
                    carinfo = carinfo.Replace("<td bgcolor=\"#ffffee\" width=\"12%\">", "");
                    carinfo = carinfo.Replace("<td bgcolor=\"#ffffee\" width=\"11%\">", "");
                    carinfo = carinfo.Replace("<td bgcolor=\"#ffffee\">", "");
                    carinfo = carinfo.Replace("\r\n", "");
                    carinfo = carinfo.Replace("&nbsp;", "");
                    carinfo = carinfo.Replace(" ", "");
                    carinfo = carinfo.Replace("号牌号码", "\"Number\":\"");
                    carinfo = carinfo.Replace("号牌种类", "\",\"CarType\":\"");
                    carinfo = carinfo.Replace("车辆状态", "\",\"CarStates\":\"");
                    carinfo = carinfo.Replace("车主", "\",\"PersonName\":\"");
                    carinfo = carinfo.Replace("住址", "\",\"Address\":\"");
                    carinfo = carinfo.Replace("行政区划", "\",\"AdministrativeDivision\":\"");
                    carinfo = carinfo.Replace("邮政编码", "\",\"PostNumber\":\"");
                    carinfo = carinfo.Replace("电话号码", "\",\"PhoneNumber\":\"");
                    carinfo = carinfo.Replace("销售单位", "\",\"SalesUnit\":\"");
                    carinfo = carinfo.Replace("证件名称", "\",\"CertificateName\":\"");
                    carinfo = carinfo.Replace("生成厂商", "\",\"Manufacturer\":\"");
                    carinfo = carinfo.Replace("证件号码", "\",\"CertificateNumber\":\"");
                    carinfo = carinfo.Replace("使用性质", "\",\"UsedNature\":\"");
                    carinfo = carinfo.Replace("车辆来历", "\",\"CarFrom\":\"");
                    carinfo = carinfo.Replace("车架号", "\",\"Framenumber\":\"");
                    carinfo = carinfo.Replace("发证机关", "\",\"CertificateOrganization\":\"");
                    carinfo = carinfo.Replace("发动机号", "\",\"EngineNumber\":\"");
                    carinfo = carinfo.Replace("出厂日期", "\",\"OutDate\":\"");
                    carinfo = carinfo.Replace("产权", "\",\"PropertyRight\":\"");
                    carinfo = carinfo.Replace("厂牌", "\",\"CarLabel\":\"");
                    carinfo = carinfo.Replace("车身颜色", "\",\"CarColor\":\"");
                    carinfo = carinfo.Replace("登记日期", "\",\"RegistrationDate\":\"");
                    carinfo = carinfo.Replace("发证日期", "\",\"CertificateDate\":\"");
                    carinfo = carinfo.Replace("有效期止", "\",\"EffectsTime\":\"");
                    carinfo = carinfo.Replace("登记证书", "\",\"RegistrationCertificate\":\"");
                    carinfo = carinfo.Replace("报废期止", "\",\"OffDate\":\"");
                }
                #endregion
            }
            catch (Exception)
            {

            }

            return "{" + carinfo + "\"}";
        }

    }

}